package com.begye.smartloan.apptest.daohang

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.util.AttributeSet
import android.view.View
import android.widget.RelativeLayout
import com.begye.smartloan.apptest.R
import com.begye.smartloan.apptest.databinding.DaoHangNavBinding

class DaoHangNav : RelativeLayout {

    private var _binding: DaoHangNavBinding? = null
    private val binding get() = _binding!!

    constructor(context: Context?) : this(context, null)
    constructor(context: Context?, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : this(
        context,
        attrs,
        defStyleAttr,
        0
    )

    @SuppressLint("Recycle")
    constructor(
        context: Context?,
        attrs: AttributeSet?,
        defStyleAttr: Int,
        defStyleRes: Int,
    ) : super(
        context,
        attrs,
        defStyleAttr,
        defStyleRes
    ) {
        context?.let {
            val layout = View.inflate(it, R.layout.dao_hang_nav, this)
            _binding = DaoHangNavBinding.bind(layout)
        }
    }

    override fun onFinishInflate() {
        super.onFinishInflate()
        // Ensure binding is not null after inflation
        if (_binding == null) {
            throw IllegalStateException("ViewBinding not initialized for ${javaClass.simpleName}")
        }
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        _binding = null  // Clear the binding reference
    }

    fun initConfig(
        text: String? = null,
        textColor: String = "#ffffff",
        leftResId: Int = R.drawable.dres_39,
        rightResId: Int = R.drawable.dres_38,
        hideLeftRes: Boolean = false,
        hideRightRes: Boolean = false,
        onClickAction: (Int) -> Unit
    ) {
        binding.viewPageNarBarText.text = text
        binding.viewPageNarBarText.setTextColor(Color.parseColor(textColor))

        binding.viewPageNarBarLeft.setOnClickListener {
            onClickAction.invoke(0)
        }
        binding.viewPageNarBarRight.setOnClickListener {
            onClickAction.invoke(1)
        }
        try {
            binding.viewPageNarBarLeft.setImageResource(leftResId)
            binding.viewPageNarBarRight.setImageResource(rightResId)

        } catch (e: Exception) {
            //
        }

        if (hideLeftRes) {
            binding.viewPageNarBarLeft.visibility = View.INVISIBLE
        } else {
            binding.viewPageNarBarLeft.visibility = View.VISIBLE
        }

        if (hideRightRes) {
            binding.viewPageNarBarRight.visibility = View.INVISIBLE
        } else {
            binding.viewPageNarBarRight.visibility = View.VISIBLE
        }
    }

}